/**
 * Copyright 2014 @ z3q.net.
 * name :
 * author : jarryliu
 * date : 2013-12-12 16:52
 * description :
 * history :
 */

package shopping

import (
    "dhfshop/models"
	"strings"
	"errors"
	"time"
	"github.com/astaxie/beego/orm"
)

//分销商折扣
type Discounts struct {
	DiscountId    int64  `orm:"column(discount_id);pk;auto" json:"discount_id" form:"discount_id"` //折扣ID 
	CompanyId     int64    `orm:"column(company_id)" json:"company_id" form:"company_id"`    //供应商ID
	TargetType    string `orm:"column(target_type)" json:"target_type" form:"target_type"` //折扣类型: GRADE（按会员等级优惠）,DISTRIBUTOR（按分销商优惠）
	TargetId      int64  `orm:"column(target_id)" json:"target_id" form:"target_id"`                //会员等级的id或者分销商id
	TargetName    string `orm:"column(target_name)" json:"target_name" form:"target_name"`          //会员等级名称或者分销商名称
	DiscountType  string `orm:"column(discount_type)" json:"discount_type" form:"discount_type"`    //优惠方式:PERCENT（按折扣优惠）,PRICE（按减价优惠）
	DiscountValue float32 `orm:"column(discount_value);digits(12);decimals(2)" json:"discount_value" form:"discount_value"` //优惠比率或者优惠价格
	CreatedAt     time.Time  `orm:"auto_now_add;column(created_at);type(datetime)" json:"-" form:"-"`   /* 创建时间 */
	CreatedAtStr  string     `orm:"-" json:"created_at" form:"-"`
	UpdatedAt     time.Time  `orm:"auto_now;column(updated_at);type(datetime)" json:"-" form:"-"` 
	UpdatedAtStr  string     `orm:"-" json:"updated_at" form:"-"`
}

func init() {
    orm.RegisterModel(new(Discounts))   
}

func AddDiscounts(m *Discounts) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func GetDiscountsById(id int64) (v *Discounts, err error) {
	o := models.GetDefaultDB()
	v = &Discounts{DiscountId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetAllDiscounts(query map[string]string, fields []string, order_by map[string]string, 
    offset int, limit int) ([]*Discounts, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Discounts))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*Discounts
	if _, err := qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdateDiscountsById(m *Discounts, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := Discounts{DiscountId: m.DiscountId}
	if err = o.Read(&v); err != nil {
		return err
	}else{
	    if _, err = o.Update(m, k...); err != nil {
		   return err
		}
	}
	return nil
}

func DeleteDiscounts(id int64) (err error) {
	o := models.GetDefaultDB()
	v := Discounts{DiscountId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}
